import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.RecursiveAction;
//通过迭代分组子线程得到18000个元素数组排序
public class runArray {
    public static void main(String[] args) {
        int startime=(int) new Date().getTime();
        long[] array = new long[18000];
        for (int i = 0; i < 18000;i++){
            int rand = (int) (Math.random()*60000);
            array[i] = rand;
        }
        SortTask task = new SortTask(array,0,array.length);
        task.compute();
        for(long i:array){
            int endtime=(int) (new Date().getTime() - startime);
            System.out.println("耗时："+endtime+"毫秒，得到"+i);
        }
    }

    private static class SortTask extends RecursiveAction {
        final long[] array;
        final int lo,hi;
        SortTask(long[] array, int lo, int hi){
            this.array = array;
            this.lo = lo;
            this.hi =hi;
        }
        protected void compute(){
            System.out.println(Thread.currentThread().getId() + "doing...");
            if(hi-lo<200){//两百一组排序
                Arrays.sort(array,lo,hi);
            }else{
                int mid = (lo + hi) >>> 1;
                invokeAll(new SortTask(array,lo,mid),new SortTask(array,mid,hi));//迭代算出其他组的排序值
                merge(lo,mid,hi);
            }
        }
        void merge(int lo,int mid,int hi){
            long[] buf= Arrays.copyOfRange(array,lo,mid);
            for (int i=0,j=lo,k=mid;i<buf.length;j++){
                array[j] = (k == hi||buf[i]<array[k])?buf[i++]:array[k++];
            }
        }
    }
}
